import aiohttp
import asyncio
import aiofiles
import os
import re

# 下载单个文件的异步函数
async def download(url):
    # 从 URL 中提取文件名并去掉不合法字符
    filename = url.split('/')[-1]
    filename = re.sub(r'[<>:"/\\|?*]', '_', filename)  # 替换非法字符为下划线

    # 确保保存文件的文件夹存在
    folder = 'c:/Files/'
    if not os.path.exists(folder):
        os.makedirs(folder)

    # 进行异步下载
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as r:
            if r.status == 200:
                # 使用 aiofiles 异步写入文件
                async with aiofiles.open(f'{folder}{filename}', 'wb') as f:
                    await f.write(await r.read())
                print(f'已完成下载: {filename}')
            else:
                print(f'下载失败: {filename}')

# 主函数，管理多个异步任务
async def main():
    Jurls = [
        "https://tse2-mm.cn.bing.net/th/id/OIP-C.5AmeaglwRvHzzdbFVQcJ-QHaNK?w=187&h=333&c=7&r=0&o=5&dpr=1.5&pid=1.7",
        "https://tse3-mm.cn.bing.net/th/id/OIP-C.1I40RvotKENNNtNFN2TjpAHaNK?w=187&h=333&c=7&r=0&o=5&dpr=1.5&pid=1.7",
        "https://tse4-mm.cn.bing.net/th/id/OIP-C.CFev6LAEXxvcqAH9BkJvMwHaNK?w=187&h=333&c=7&r=0&o=5&dpr=1.5&pid=1.7"
    ]

    tasks = []  # 存放所有下载任务
    for url in Jurls:
        tasks.append(download(url))  # 将每个下载任务加入任务列表

    # 等待所有任务完成
    await asyncio.gather(*tasks)

# 运行主函数
if __name__ == "__main__":
    asyncio.run(main())  # 启动异步事件循环
